import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'
import { useUserStore } from '@/stores'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

// 白名单
// const whiteList = ['/', '/login', '/register']

router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta && to.meta.title) {
    document.title = to.meta.title
  } else {
    document.title = '星轻食'
  }

  const useStore = useUserStore()
  if (to.meta.requiresAuth && !useStore.user.token) {
    // 如果路由需要身份验证且用户未登录，重定向到登录页面
    next({ path: '/login', query: { redirect: to.fullPath } })
  } else {
    next()
  }
})

export default router
